<template>
	<view class="page" v-if="detail">
		<view class="base-info">
			<view class="text-info flex">
				<view class="pic mar-right12">
					<image :src="'https://www.worldintek.com:39011/yaolexue-service/'+detail.imageDto.compressLink"></image>
				</view>
				<view class="text flex1">
					<view class="flex justify-between padd-bottom22 align-start">
						<view class="cr-333 font_s34 flex1" >{{detail.title}}</view>
						<view class="subscribe-btn" v-if="detail.subscribeStatus===0" @click="handleClickSubscribe(1)">
							订阅</view>
						<view class="subscribe-btn" v-if="detail.subscribeStatus===1" @click="handleClickSubscribe(0)">
							取消订阅</view>
					</view>
					<view class="introduce">
						<t-readmore color="#000" labelColor="#FA312A" iSinfo line='2' :content="detail.description"></t-readmore>
					</view>
				</view>
			</view>
			<view class="flex justify-between mar-top41">
				<view class="ll-box flex align-center">
					<view class="font_s28 cr-333">
						播放
						<text class="mar-left35">{{detail.clickNumber}}</text>
					</view>
				</view>
				<view class="ll-box flex justify-between align-center">
					<view class="font_s28 cr-333">
						点赞
						<text class="mar-left35">{{detail.likeNumber}}</text>
					</view>
					<!--   <view>
            <image src="/static/img/icon_zan.png" class="w-26 h-26"></image>
          </view> -->
				</view>
			</view>
		</view>
		<view class="list-box padd-top30 padd-left35 padd-right30 padd-bottom40">
			<view class="label flex justify-between mar-bottom48">
				<view class="flex align-baseline">
					<view class="num font_s38 mar-right7">{{detail.contentItemAudioDtos.length}}</view>
					<view class="font_s24 cr-999">条音频</view>
				</view>
				<view class="paly-btn flex align-center ">
					<view class="play-icon mar-right7 flex align-center">
						<image src="https://www.worldintek.com:39011/yaolexue-service/icon_playCircle.png"></image>
					</view>
					<view class="font_s24" @click="handleClickPlayAll">全部播放</view>
				</view>
			</view>
			<view class="list">
				<view v-for="(item,index) in detail.contentItemAudioDtos"
					class="list-item flex justify-between align-start  mar-bottom51">
					<view class="left flex align-center">
						<view :class="[currentPlayId==item.id&&'circle','pic', 'mar-right20']"
							@click="handleClickAudio(item)">

							<!-- <image src="/static/logo.png"></image> -->



							<view :class="[currentPlayId==item.id&&'cmin',processValue!=0&&'animation-class']"
							
								:style="[{'animation-play-state':(currentPlayId==item.id&&state==1)?'running':'paused'}]">
								<view class="text">
									{{index+1}}
								</view>

							</view>
							<!-- #ifdef MP-WEIXIN -->
							<van-circle class="van-circle" v-if='currentPlayId==item.id&&processValue/fillProcessValue!=0' :value="(processValue/fillProcessValue)*100" stroke-width="1" :size='processWpx' color='#fa312a' layer-color='transparent'/>
							<!-- #endif -->
							<!-- #ifdef H5 -->
								<view class="van-circle">
									<svg viewBox="0 0 1040 1040">
										<path class="van-circle__layer"
											d="M 520 520 m 0, -500 a 500, 500 0 1, 1 0, 1000 a 500, 500 0 1, 1 0, -1000"
											style="fill: none; stroke-width: 40px;"></path>
										<path d="M 520 520 m 0, -500 a 500, 500 0 1, 1 0, 1000 a 500, 500 0 1, 1 0, -1000"
											class="van-circle__hover"
											:style="[{'stroke-width':`${showProcess?41:0}rpx`, 'stroke-dasharray':`${processValue}px, ${fillProcessValue}px`}]">
										</path>
									</svg>
									<!-- <view class="van-circle__text">0%</view> -->
								</view>
							<!-- #endif -->
						
							 
						</view>
						<view>
							<view class="font_s24 mar-bottom6" :class="[currentPlayId==item.id?'cr-FA312A':'cr-333']"
								@click="handleClickAudio(item)">
								{{item.title}}
							</view>
							<view class="cr-999 font_s20 flex">
								<view class="value-item flex align-center">
									<view class="mar-right8 icon-box">
										<image src="https://www.worldintek.com:39011/yaolexue-service/icon_touting.png"></image>
									</view>
									{{item.clickNumber}}
								</view>
								<view class="value-item flex align-center">
									<view class="mar-right8 icon-box " @click="handleClickLike(item)">
										<image v-if="item.likeStatus===0" src="https://www.worldintek.com:39011/yaolexue-service/icon_zan.png"
											class="w-26 h-26"></image>
										<image v-if="item.likeStatus===1" src="https://www.worldintek.com:39011/yaolexue-service/icon_zan_active.png"
											class="w-26 h-26"></image>
									</view>
									{{item.likeNumber}}
								</view>
								<!-- 	<view class="value-item flex align-center">
							<view class="mar-right8 icon-box">
								<image src="/static/img/icon_time.png"></image>
							</view>
							09:17
						</view> -->
							</view>
						</view>
					</view>
					<view class="right" @click.stop="handleClickCollection(item)">
						<image v-if='item.collectionStatus===0' src="https://www.worldintek.com:39011/yaolexue-service/icon_start.png"></image>
						<image v-if='item.collectionStatus===1' src="https://www.worldintek.com:39011/yaolexue-service/icon_start_active.png"></image>
					</view>
				</view>
			</view>
		</view>
		<!-- 	<u-popup
	class="favorites-popup"
	  :show="showFavoritesPopup"
	  mode="bottom"
	  @close="handleUpdateContentCollectionStatus"
	  
	>
	  <view class="favorites-pop padd-top30 padd-left32 padd-right32">
	    <view class="flex justify-between mar-bottom31">
			<view class="font_s28 cr-333 font_w500 ">
				选择收藏夹
			</view>
			<view class="font_s24 cr-999" @click="handleShowCollctPopup(true)">
				<image src="/static/img/icon_add.png" mode="" class="w-21 h-21 mar-right10"></image>
				新建收藏夹
			</view>
		</view>
	    <view class="content ">
	      <view class=" mar-bottom19 item" v-for="item in favoritesList">
			 <radio-group  @change="radioChange">
						<label class="flex justify-between"  >
							
							<view>
								<view class="cr-333 font_s26 mar-bottom17">
									{{item.favoritesName}}
								</view>
								<view class="cr-999 font_s24">
									10个内容
								</view>
							</view>
							<view>
								<radio  :value="item.id" :checked="activeFavorites.id==item.id" />
							</view>
						</label>
					
			</radio-group>
	      </view>
	    </view>
	  </view>
	</u-popup> -->
		<t-favoritespop :show='showFavoritesPopup' :faChild='item'
			@close='()=>{handleShowFaPopup(false);init()}'></t-favoritespop>
		<!-- 	<u-popup
	      :show="showCeateCollectPopup"
	      mode="center"
	      @close="handleShowCollctPopup(false)"
	      closeable
	    >
	      <view class="createcollect-pop padd-top30 padd-left32 padd-right32">
	        <view class="font_s28 cr-333 mar-bottom31">创建收藏夹</view>
	        <view class="content padd-bottom30">
	          <view class="flex mar-bottom19 ">
								<u-input type="text" v-model="favoritesName" placeholder="请输入收藏夹名称"></u-input>
	          </view>
						<u-button type="primary" text="确定" @click="handleAddUserFavorites"></u-button>
	        </view>
	      </view>
	    </u-popup> -->
	</view>
</template>
<script>
import formItem from '../../uni_modules/uview-ui/libs/config/props/formItem';
	export default {
		data() {
			return {
        intervalID:null,
				id: '',
				detail: null,
				collectionParams: {
					collectionStatus: null,
					contentItemId: null,
					userFavoritesId: null,
				},
				showFavoritesPopup: false,
				// showCeateCollectPopup: false,
				// favoritesList:[],
				// activeFavorites:null,
				// favoritesName:'',
				item: null,
				currentPlayId: null,
				processValue: 0, //当前进度条进度
				fillProcessValue: 3140, //圆环进度条总长度
				showProcess: false, //显示进度条
				state: 0, //0未开始，1播放，2暂停
				step: 0, //总长度/时间，速度
				timer:[],//用于切换清除定时器
				processWpx:0,
				innerAudioContext:null,//音频实例
				playAll:0,//0 ，1进入播放全部状态，
        pt:'',
			}
		},
		beforeDestroy() {
			this.handleClearAllMusic()
		},
		onLoad(payload) {
      this.getPt()
			if (payload.cid) {
				this.currentPlayId = payload.cid
				console.log(this.currentPlayId);
			}
			if (payload.id) {
				this.id = payload.id
				this.init()
			}
			function rpxToPx(rpx) {
			  // 获取屏幕宽度
			  const windowWidth = uni.getSystemInfoSync().windowWidth;
			  // 小程序宽度基准为750rpx
			  const baseWidth = 750;
			  // 计算比例
			  const factor = windowWidth / baseWidth;
			  // 返回px值
			  return rpx * factor;
			}
			
			let rpxValue = 99;
			this.processWpx = rpxToPx(rpxValue);
			console.log(1111,this.processWpx)
		},
		onShareAppMessage(res) {
			this.$postShareHttp(this.id)
		    return {
		      title: this.detail.title,
		      path: `/pages/AudioItemList/AudioItemList?id=${this.id}&cid=${this.currentPlayId}`
		    }
		},
		methods: {
			getPt(){
        try {
          const systemInfo = uni.getSystemInfoSync();
          if(systemInfo.platform == 'ios') {
            // 当前环境是iOS
            console.log('运行在iOS环境');
            this.pt='ios'
          } else if(systemInfo.platform == 'android') {
            // 当前环境是Android
            console.log('运行在Android环境');
            this.pt='android'
          } else {
            // 其他环境
            console.log('其他环境，平台标识：' + systemInfo.platform);
          }
        } catch (e) {
          console.log('获取系统信息失败');
        }
      },
			init() {
				this.getDetail()
			},
		
			async getDetail() {
				return this.$http.get(
					`/yaolexue-service-portal/contentItem/contentAudioPlayInfo/` + this.id, {}, {
						isNeedLoading: true
					}).then(res => {
					console.log(res)
					this.detail = res.data
				})
			},
			//获取收藏夹
			// getUserFavorites(){
			// 	return this.$http.get(
			// 		`/yaolexue-service-portal/userFavorites/findUserFavorites`, {}, {
			// 			isNeedLoading: true
			// 		}).then(res=>{
			// 			this.favoritesList=res.data
			// 			this.activeFavorites=res.data.find(item=>item.defaultStatus)||res.data[0]//后台还需要增加字段默认收藏夹选中和改变收藏夹选择

			// 		})

			// },
			//点击订阅
			handleClickSubscribe(status) {
				return this.$http.put(
					`/yaolexue-service-portal/contentItem/updateAlbumSubscribeStatus`, {
						albumId: this.detail.id,
						subscribeStatus: status
					}, {
						isNeedLoading: true
					}).then(res => {
					if (res.code === 200) {
						this.getDetail()
					}
				})
			},
			//点击播放音乐上报
			handleEscalation(){
				return this.$http.post(
					`/yaolexue-service-portal/contentItem/contentAudioPlay/${this.currentPlayId}`, {
					}, {
						isNeedLoading: true
					}).then(res => {
				})
			},
			//点击收藏
			handleClickCollection(item) {
				this.item = item
				if (item.collectionStatus === 0) {
					this.handleShowFaPopup(true)
				} else {
					this.handleUpdateContentCollectionStatus()
				}
			},
			//	点击播放全部
			handleClickPlayAll(){
			const audioList=	this.detail.contentItemAudioDtos
			if(audioList.length){
				this.playAll=1
				this.handleClickAudio(audioList[0])
			}
			},
			//点击音频项
			handleClickAudio(audio) {
				console.log(audio)
				this.item = audio
				// const time = this.item.time || 200 // 获取整首音乐的时间 单位s
				// this.step = this.fillProcessValue / time
				//点击已播放完毕的音乐，重新播放
				console.log(this.state == 0, 'this.state ==0')
				if (this.currentPlayId !== audio.id || this.state == 0) {
					//切换音乐或者重新播放
					this.handleClearAllMusic()

					this.$nextTick(() => {
						this.showProcess = true
						this.currentPlayId = audio.id;
						this.state = 1
						this.handlePlayMusic()
            this.handleEscalation()
																																																																		})
				} else {
					//
					if (this.state == 2) {
						//暂停状态下重启音乐
						this.state = 1
						this.handlePlayMusic()
					} else if (this.state == 1) {
						//暂停音乐
						this.handleStopMusic()
					}
				}

			},
			//销毁所有音频播放
			handleClearAllMusic() {
				if (this.innerAudioContext) {
				  try {
				    this.innerAudioContext.pause();
				    this.innerAudioContext.destroy()
				   this. innerAudioContext = null
				  } catch (e) {
				    //TODO handle the exception
				  }
				}
        this.intervalID=null
				this.showProcess = false
				this.processValue = 0
				this.state = 0
				for(let i = 0; i < this.timer.length; i++) {
				    clearTimeout(this.timer[i]);
				}
			},
			//暂停音频播放
			handleStopMusic() {
				if (this.innerAudioContext) {
				  try {
				    this.innerAudioContext.pause();
	
				  } catch (e) {
				    //TODO handle the exception
				  }
				}
				this.state = 2
			},
			//开始播放当前音乐
			handlePlayMusic() {
				if(!this. innerAudioContext ){
          // if(this.pt=='ios'){
          //   this. innerAudioContext =	uni.getBackgroundAudioManager()
          // }else{
           
          // }
				this. innerAudioContext =	uni.createInnerAudioContext({
				  obeyMuteSwitch :false
				})
							this.innerAudioContext.src ='https://www.worldintek.com:39011/yaolexue-service/'+this.item.imageDto.originalLink;
							// this.innerAudioContext.src = 'http://dworldintek.com:39011/mall/yinping.mp3' ;
							this.innerAudioContext.onPlay((e)=>{
                console.log(e,'开始播放了')
              })
							this.innerAudioContext.onCanplay((E)=>{
                console.log(E,'可以播放了')
                this.innerAudioContext.play()//这里进不来所以提来
							this.intervalID = setInterval(() => {
                console.log(this.innerAudioContext.duration,'this.innerAudioContext.duration')
							    if (this.innerAudioContext.duration !== 0) {
							      clearInterval(this.intervalID); // 清除定时器
                    this.intervalID=null
							  // this.innerAudioContext.play()//这里进不来所以提出去
                    this.innerAudioContext.onTimeUpdate((E)=>{
                      console.log(E,'播放时间变化')
                      this.processRun()
                    })
							    }
							  }, 200);
							})
            
							this. innerAudioContext.onEnded(()=>{
								this.state = 0
								if(this.processValue!=this.fillProcessValue){
									//因为读取的播放的时间有偏差所以手动设置已达到完播状态
									this.processValue=this.fillProcessValue
								}
								
								//全部播放状态下进入下一首播放
								setTimeout(()=>{
									console.log(this.playAll==1,'this.playAll==1')
									if(this.playAll==1){
										const audioList=	this.detail.contentItemAudioDtos
										const curIndex=audioList.findIndex(item=>item.id==this.currentPlayId)
										console.log(curIndex)
										if(curIndex!==audioList.length-1){
											//不是最后一首
											this.handleClickAudio(audioList[curIndex+1])
										}else{
											//全部播放完毕
											this.playAll=0
										}
										
									}
								},100)
							
							
							})
				}else{
					this.innerAudioContext.play()
				}
		
				
			},
			processRun() {
				const audioSchedule=this.innerAudioContext.currentTime/this.innerAudioContext.duration
				this.processValue =audioSchedule*this.fillProcessValue
		
				
				// if (this.processValue == this.fillProcessValue) this.state = 0
				
				// const timer= setTimeout(() => {
				// 	console.log('processValue', this.processValue)
				// 	if (this.processValue < this.fillProcessValue && this.state == 1) {
				// 		const offsetValue = this.fillProcessValue - this.processValue;
				// 		this.processValue += (offsetValue < this.step ? offsetValue : this.step)
				// 		this.processRun();
				// 		if (this.processValue == this.fillProcessValue) this.state = 0
				// 	}
				// }, 1000);
				// this.timer.push(timer)
			},
			//添加收藏夹
			// handleAddUserFavorites(){
			// 	return this.$http.post(
			// 		`/yaolexue-service-portal/userFavorites/addUserFavorites`, {
			// 			favoritesName:this.favoritesName,
			// 		}, {
			// 			isNeedLoading: true
			// 		}).then(res=>{
			// 			if(res.code===200){
			// 	this.handleShowCollctPopup(false)
			// 				 this.getUserFavorites()
			// 			}
			// 		})
			// },

			//改变收藏状态
			handleUpdateContentCollectionStatus() {
				this.handleShowFaPopup(false)
				// this.handleShowCollctPopup(false)

				const collectionParams = {
					collectionStatus: 1 - this.item.collectionStatus,
					contentItemId: this.item.id,
				}
				// if(this.activeFavorites){
				// 	collectionParams.userFavoritesId=this.activeFavorites.id
				// }
				return this.$http.put(
					`/yaolexue-service-portal/contentItem/updateContentCollectionStatus`, collectionParams, {
						isNeedLoading: true
					}).then(res => {

					if (res.code === 200) {
						this.getDetail()
					}
				})
			},
			//显示收藏夹弹窗
			handleShowFaPopup(flag) {
				// if(flag)this.getUserFavorites()
				this.showFavoritesPopup = flag;
			},
			//显示新建收藏夹弹窗
			// handleShowCollctPopup(flag){
			// 	this.showCeateCollectPopup = flag;
			// },
			//选择收藏夹
			// radioChange(evt){

			// 	this.activeFavorites=this.favoritesList.find(item=>item.id===evt.detail.value)

			// },
			//点击点赞
			handleClickLike(item) {
				return this.$http.put(
					`/yaolexue-service-portal/contentItem/updateContentLikeStatus`, {
						contentItemId: item.id,
						likeStatus: 1 - item.likeStatus
					}, {
						isNeedLoading: true
					}).then(res => {

					if (res.code === 200) {
						this.getDetail()
					}
				})
			},
		},
	};
</script>
<style lang="scss">
	$roundW: 99rpx;
	$roundH: 99rpx;

	$roundcr: #d7d7d7;

	.cr-FA312A {
		color: #FA312A
	}



	.page {
		background-color: rgba(4, 0, 0, 0.09);
		overflow: auto;
	}

	view.base-info {
		padding: 30rpx 33rpx 72rpx;

		view.text-info {
			view.pic {
				width: 209rpx;
				height: 150rpx;
				flex: 0 0 209rpx;

				image {
					width: 100%;
					height: 100%;
				}
			}

			view.text {
				view.subscribe-btn {
					font-size: 24rpx;
					font-weight: 400;
					color: #ffffff;
					background: #fa312a;
					border-radius: 10rpx;
					padding: 8rpx 30rpx;
				}

				view.introduce {}
			}
		}

		.ll-box {
			width: 327rpx;
			height: 52rpx;
			background: #d7d7d7;
			padding: 0 20rpx;
		}
	}

	.list-box {
		background-color: #fff;

		.label {
			align-items: baseline;

			.num {
				color: #d3b941;
			}

			.paly-btn {
				background: rgba(250, 49, 42, 0.32);
				border-radius: 19rpx;
				color: #fa312a;
				padding: 8rpx 12rpx;

				.play-icon {
					width: 21rpx;
					height: 21rpx;

					image {
						width: 100%;
						height: 100%;
					}
				}
			}
		}

		.list {
			.left {
				.pic {
					width: $roundW;
					height: $roundH;
					display: flex;
					justify-content: center;
					align-items: center;

					// image {
					// 	width: 100%;
					// 	height: 100%;
					// }
					.text {
						// width: 63rpx;
						// height: 51rpx;
						font-size: 72rpx;
						font-family: SimSun;
						font-weight: 400;
						color: #FFFFFF;
						text-align: center;
						background: linear-gradient(179deg, #2C2306 0%, #969696 100%);
						-webkit-background-clip: text;
						-webkit-text-fill-color: transparent;
					}
				}

				.circle {
					position: relative;

					.animation-class {
						animation-name: circlemv;
					}

					.cmin {
						// margin: 50px auto;
						position: relative;
						display: flex;
						justify-content: center;
						align-items: center;
						width: 100%;
						height: 100%;
						border-radius: 50%;

						background-color: $roundcr;
						// animation:  circlemv 4s linear 0.1s infinite
						animation-duration: 4s;
						animation-timing-function: linear;
						animation-delay: 0.1s;
						animation-iteration-count: infinite;
						// .offsetCircle{
						// 	position: absolute;right: 4rpx;
						// 	top: 4rpx;
						// 	width: calc(100% - 8rpx);
						// 	height: calc(100% - 8rpx);
						// 	border-radius: 50%;
						// 	outline: 4rpx solid #FA312A;
						// }

					}

					.van-circle {
						position: absolute;
						width: 100%;
						height: 100%;

						svg {
							position: absolute;
							top: 0;
							left: 0;
							width: 100%;
							height: 100%;

							.van-circle__layer {
								stroke: #d7d7d7;
							}

							.van-circle__hover {
								fill: none;
								stroke: #fa312a;
								stroke-linecap: round;
							}
						}
					}


				}
			}

			.right {
				width: 27rpx;
				height: 27rpx;

				image {
					width: 100%;
					height: 100%;
				}
			}

			.value-item {
				width: 113rpx;

				.icon-box {
					width: 28rpx;
					height: 28rpx;

					image {
						width: 100%;
						height: 100%;
					}
				}
			}
		}
	}

	

	.createcollect-pop {
		width: 400rpx;


	}

	@keyframes circlemv {


		25% {
			transform: rotate(90deg);
		}

		50% {
			transform: rotate(180deg);
		}

		75% {
			transform: rotate(270deg);
		}

		100% {
			transform: rotate(360deg);
		}
	}


	//      .circle .cmin{

	//          width: 60px;
	//          height: 60px;
	//          border: 1px solid #000; 
	//          background: #eee;
	//          border-radius: 50%;
	//          position: absolute;
	// top: 0;
	// left: 0;
	//          // top: 160px;
	//          // left: 120px;
	// }
	//      .circle .cmin .cminmin{
	//          width: 18px;
	//          height: 18px; 
	//          background: #fff;
	//          border: 1px solid #000;
	//          border-radius: 50%;
	//          position: absolute;
	//          top: 21px;
	//          left: 21px;
	//          opacity: 0.4}
</style>